package com.rjkj.medicalwaste.ui.collect

import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.bean.CodeType
import com.rjkj.medicalwaste.bean.Decoder04Bean
import com.rjkj.medicalwaste.bean.MedicalWasteType
import com.rjkj.medicalwaste.bean.UserBean
import com.rjkj.medicalwaste.databinding.FragmentCollectOneBinding
import com.rjkj.medicalwaste.databinding.FragmentCollectOnePreBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.ui.my.NumberEditInputFilter
import com.rjkj.medicalwaste.utils.Encoder03Small
import com.rjkj.medicalwaste.utils.StringUtils
import com.rjkj.medicalwaste.utils.TimeUtils
import com.rjkj.medicalwaste.viewmodels.BluetoothControlViewModel
import com.rjkj.medicalwaste.viewmodels.CollectMainViewModel
import com.rjkj.medicalwaste.viewmodels.CollectOneViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 预制二维码收集界面
 * @property preCodeArgs CollectOneFragment2Args
 */
class CollectOneFragment2 : BaseFragment<FragmentCollectOnePreBinding>() {
    private val preCodeArgs: CollectOneFragment2Args by navArgs()
    private val bluetoothControlViewModel: BluetoothControlViewModel by activityViewModels()
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }
    private val collectOneViewModel: CollectOneViewModel by viewModels {
        MainViewModelProvider.providerCollectOneModel(requireContext())
    }
    private val viewModel: CollectMainViewModel by activityViewModels {
        MainViewModelProvider.providerCollectMainModel(requireContext())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentCollectOnePreBinding.inflate(inflater, container, false)
        onSubscribeUi(binding)
        binding.bluetoothData = bluetoothControlViewModel
        binding.userData = userViewModel
        binding.lifecycleOwner = viewLifecycleOwner
        return binding.root
    }

    private fun getMedicalWasteTypeByPreCode(preCode: String): MedicalWasteType {
        return if (preCode.isNotEmpty() && preCode.length >= 2) {
            when (preCode.substring(0, 2)) {
                "11" -> MedicalWasteType.XG
                "10" -> MedicalWasteType.GRX
                "20" -> MedicalWasteType.SSX
                "21" -> MedicalWasteType.SSX
                "30" -> MedicalWasteType.BLX
                "40" -> MedicalWasteType.YWX
                "50" -> MedicalWasteType.HXX
                else -> MedicalWasteType.NUllType
            }
        } else
            MedicalWasteType.NUllType
    }

    override fun onSubscribeUi(binding: FragmentCollectOnePreBinding) {
        initTip(collectOneViewModel)
        if (userViewModel.setting.value?.infoMode == 1) {
            binding.tvWeight.setOnClickListener {
                addWeightDialog()
            }
        } else {
            binding.tvWeight.setOnLongClickListener {
                addWeightDialog()
                false
            }
        }

        collectOneViewModel.preCode.observe(viewLifecycleOwner) {
            if (it.isEmpty()) {
                binding.imTypeColor.setImageResource(R.color.white)
                binding.tvCode.text = it
                binding.tvType.text = it
            } else {
                val medicalWasteType = getMedicalWasteTypeByPreCode(it)
                if (medicalWasteType == MedicalWasteType.NUllType) {
                    showTip("未知类型")
                } else {
                    binding.imTypeColor.setBackgroundColor(resources.getColor(medicalWasteType.colorId))
                    binding.tvCode.text = it
                    binding.tvType.text = medicalWasteType.typeName
                }
            }
        }
        collectOneViewModel.preCode.value = preCodeArgs.preCode
        binding.imBack.setOnClickListener {
            requireActivity().onBackPressed()
        }
        binding.btBack.setOnClickListener {
            requireActivity().onBackPressed()
        }
        bluetoothControlViewModel.startRec()
        binding.tvZero.setOnClickListener {
            bluetoothControlViewModel.zeroRec()
        }
        binding.btOk.setOnClickListener {
            addGarbage()
        }
        LiveDataBus.get().with(MainActivity.SCAN_DATA, String::class.java).observe(
            viewLifecycleOwner, {
//                showTip(it)
                val split = it.split("?")
                if (split.size == 2 && StringUtils.checkTagRealness(split[1])) {
                    collectOneViewModel.preCode.value = split[1]
                } else {
                    showTip("请勿扫描其他二维码")
                }
            }
        )
    }

    private fun addGarbage() {
        val garbageQRCode = "1" + collectOneViewModel.preCode.value
        val medicalWasteType = getMedicalWasteTypeByPreCode(collectOneViewModel.preCode.value ?: "")
        if (medicalWasteType == MedicalWasteType.NUllType) {
            showTip("选择正确的类型")
            return
        }
        val timeStr = TimeUtils.getTimeStr()
        val weight = bluetoothControlViewModel.decoder04Bean.value?.weight ?: "0"
        if (collectOneViewModel.time == timeStr) {
            showTip("请稍后再试")
            return
        } else {
            collectOneViewModel.time = timeStr
        }
        if (weight.toFloat() < 0) {
            showTip("重量为负")
            return
        } else if (weight.toFloat().compareTo(0) == 0) {
            showTip("重量为0")
            return
        }
        lifecycleScope.launch {
            val department = userViewModel.departmentUser.value ?: UserBean()
            val nurse = userViewModel.nurseUser.value ?: UserBean()
            val user = userViewModel.cleanerUser
            val serialNum = userViewModel.getSerial()
            Log.e(TAG, "addGarbage:$serialNum ")
            Log.e(TAG, "addGarbage: $garbageQRCode")
            val addGarbage = collectOneViewModel.addGarbage2(
                userViewModel.getSerial(),
                garbageQRCode,
                weight,
                medicalWasteType,
                userViewModel.hospitalId.value ?: "",
                user,
                nurse,
                department
            )
            if (addGarbage != null) {
                viewModel.addGarbageToList(addGarbage)
                val encoder03Small = Encoder03Small()
                //袋模式1，箱模式：2
                encoder03Small.setQRcode("1", garbageQRCode, userViewModel.hospitalId.value)
                encoder03Small.setGarbage(
                    userViewModel.hospitalName.value,
                    department.name,
                    weight + "KG",
                    medicalWasteType.typeName,
                    user.name,
                    nurse.name,
                    TimeUtils.getYMDTime()
                )
                LiveDataBus.get().with("Print").postValue(encoder03Small)
                findNavController().navigateUp()
            } else {
                showTip("已存在医废")
                collectOneViewModel.preCode.value = ""
            }

        }
    }

    private fun addWeightDialog() {
        val et = EditText(requireContext())
        et.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
        et.filters = arrayOf(NumberEditInputFilter(100))
        AlertDialog.Builder(requireContext())
            .setTitle("请输入重量")
            .setView(et)
            .setPositiveButton("确定", DialogInterface.OnClickListener { _, i -> //按下确定键后的事件
                val toString = et.text.toString()
                if (toString.isNotEmpty()) {
                    bluetoothControlViewModel.decoder04Bean.value = Decoder04Bean().apply {
                        weight = toString
                    }
                } else {
                    showTip("未输入重量")
                }
            }).setNegativeButton("取消", null).show()
    }

    override fun onDestroyView() {
        bluetoothControlViewModel.stopRec()
        super.onDestroyView()
    }

}